package com.chengyi.serialport.demo.activity

import android.widget.TextView
import androidx.databinding.ObservableField
import com.chengyi.serialboard.sdk.SerialPortOptions
import com.chengyi.serialport.demo.R
import com.chengyi.serialport.demo.databinding.ActivityJiePuWeiPrinterBinding
import com.chengyi.serialport.demo.printer.JpwPrinterSerialPortUtil
import com.print.usbprint.command.Label
import me.goldze.mvvmhabit.binding.command.BindingAction
import java.text.SimpleDateFormat
import java.util.Date

class ActivityJiePuWeiPrinter : BaseActivity<ActivityJiePuWeiPrinterBinding, ActivityJiePuWeiPrinter.ViewModel>() {
    override fun getLayoutRes(): Int = R.layout.activity_jie_pu_wei_printer
    override fun initViews() {
        initBar(binding.myTopBar)
    }

    class ViewModel : BaseSerialPortViewModel<JpwPrinterSerialPortUtil>() {
        override val serialportPath = ObservableField("/dev/ttyS1")
        override val baudrate = ObservableField("115200")
        override val textHex: TextView?
            get() = uiChangeLiveData.getBinding<ActivityJiePuWeiPrinterBinding>()?.textHex

        override fun createSerialPortUtil(path: String, baudrate: Int): JpwPrinterSerialPortUtil? {
            val options = SerialPortOptions().path(path).baudrate(baudrate).txConnect(SerialPortOptions.RX).rxConnect(SerialPortOptions.TX).useGND(true)
            return JpwPrinterSerialPortUtil(options, object : JpwPrinterSerialPortUtil.Callback {
                override fun onSendCallback(hex: String) {
                    onSerialPortSendCallback(hex)
                }

                override fun onReceiverCallback(hex: String) {
                    onSerialPortReceiveCallback(hex)
                }
            })
        }

        val onDemo1PrintClick = BindingAction {
            val label = Label()
            label.reset()
            label.switchLabel()
            label.customPageStart(52 * 8, 40 * 8, 0)
            val xPianyi = 20
            val yPianyi = 20
            val fontPx = 24
            val lineHeight = 8
            var y = yPianyi
            val title = "山东XXX信息科技有限公司"
            label.customPrintText("企业：", xPianyi, y, fontPx, 0, 0, 0, 0, 0, 1, 1)
            label.customPrintText(title, xPianyi + fontPx * 3, y, fontPx, 0, 0, 0, 0, 0, 1, 1)
            y += fontPx + lineHeight
            label.customPrintText("打印时间：${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}", xPianyi, y, fontPx, 0, 0, 0, 0, 0, 1, 1)
            label.pageEnd()
            label.customPrintPage(1)
            runSerialPortCommand {
                it.doPrint(label)
            }
        }

    }
}